import axios from 'axios'
import { ElMessage, ElMessageBox, ElLoading  } from 'element-plus'
import { store } from '@/store'
import router from '@/router'

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASEURL,
  timeout: 5000 * 10
})

// 控制登录过期的锁
let isRefreshing = false
let loadingInstance 
// 请求拦截器
request.interceptors.request.use(
  (config) => {
    loadingInstance = ElLoading.service({
      // background: 'rgba(0,0,0,0.5)',
      text: '数据加载中,请稍后',
      fullscreen: false,
      target:'#el-main'
    })
    // 统一设置用户身份token
    const user = store.state.user
    if (user && user.token) {
      config.headers.Authorization = `Bearer ${user.token}`
    }
    console.log(config, '=========')
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    loadingInstance && loadingInstance.close()
    let status = response.data.status
    if (!status || status === 200) {
      return response.data.result
    }
    // 登录过期
    if (status === 410000) {
      // 防止同一时间,有多个请求,避免重复弹框
      if (isRefreshing) {
        return Promise.reject(response)
      }
      isRefreshing = true
      ElMessageBox.confirm('您的登录已过期,您可以取消停留在此页面,或确认重新登录?', '登录过期', {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      })
        .then(() => {
          store.commit('setUser', null)
          router.push({
            name: 'login',
            query: {
              redirect: router.currentRoute.value.fullPath
            }
          })
        })
        .finally(() => {
          isRefreshing = false
        })
      //在内部消化掉业务异常
      return Promise.reject(response)
    } else {
    }
  },
  (error) => {
    loadingInstance && loadingInstance.close()
    console.log(error)
    let errorMessage = ''
    if (error.response) {
      // 请求发送成功，响应接收完毕，但是状态码为失败
      const { status } = error.response
      if (status === 400) {
        errorMessage = '请求参数错误'
      } else if (status === 403) {
        errorMessage = '没有权限，请联系管理员'
      } else if (status === 404) {
        errorMessage = '请求资源不存在'
      } else if (status === 500) {
        errorMessage = '服务端错误'
      }
    } else if (error.request) {
      // 请求发送成功，但未收到响应
      errorMessage = '请求超时，请稍后重试'
    } else {
      // 意料之外的错误
      errorMessage = error.message
    }
    ElMessage.error(errorMessage)
    return Promise.reject(error)
  }
)

// export default request

export default request
